package com.hjl.web.servlet;

import cn.hutool.captcha.LineCaptcha;
import com.hjl.domain.PageBean;
import com.hjl.domain.ResultInfo;
import com.hjl.domain.User_inf;
import com.hjl.service.UserService;
import com.hjl.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

/**
 * 管理账户表现层
 *
 * @author Lenovo
 * @version 1.0
 * @date 2021/10/8 9:59
 */
@WebServlet("/user/*")
public class UserServlet extends BaseServlet {
    private UserService userService = new UserServiceImpl();
    String prefix = "/WEB-INF/jsp/users/";
    String suffix = ".jsp";

    /**
     * 跳转WEB-INF里的jsp
     *
     * @author Lenovo
     * @date 2021/10/8 10:00
     */
    public void toList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher(prefix + "userlist" + suffix).forward(req, resp);
    }

    public void toAdd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher(prefix + "useradd" + suffix).forward(req, resp);
    }

    public void toEdit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher(prefix + "useredit" + suffix).forward(req, resp);
    }

    /**
     * 管理账户登录
     *
     * @author Lenovo
     * @date 2021/10/8 10:01
     */
    public void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取输入的验证码
        String checkCode = req.getParameter("checkcode");
        //得到验证码对象
        LineCaptcha right = (LineCaptcha) req.getSession().getAttribute("right");
        //验证码结果
        boolean res = right.verify(checkCode);
        //将结果保存在ResultInfo中
        ResultInfo info = new ResultInfo();
        info.setFlag(res);
        info.setErrorMsg("验证码错误");
        if (res) {
            //把验证码数据删除
            req.getSession().removeAttribute("right");
            //获取数据
            Map<String, String[]> map = req.getParameterMap();
            User_inf user = new User_inf();
            try {
                //封装
                BeanUtils.populate(user, map);
            } catch (IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
            //调用service方法
            User_inf u = userService.login(user);

            //判断登录结果
            if (u == null) {
                info.setFlag(false);
                info.setErrorMsg("用户名或密码错误");
            }
            if (u != null && u.getStatus() == 0) {
                info.setFlag(false);
                info.setErrorMsg("未审核，请联系管理员审核");
            }
            if (u != null && u.getStatus() == 1) {
                info.setFlag(true);
                req.getSession().setAttribute("user", u);
            }
        }
        writeValue(info, resp);
    }

    /**
     * 管理账户注销
     *
     * @author Lenovo
     * @date 2021/10/8 10:02
     */
    public void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取session，删除
        HttpSession session = req.getSession();
        if (session != null) {
            session.removeAttribute("user");
        }
        resp.sendRedirect(req.getContextPath() + "/loginForm.jsp");
    }

    /**
     * 分页查找管理账户
     *
     * @author Lenovo
     * @date 2021/10/8 10:02
     */
    public void findUserByPage(HttpServletRequest req, HttpServletResponse resp) throws
            ServletException, IOException {
        //中文乱码问题
        req.setCharacterEncoding("utf-8");
        //获取数据（当前页码和行数）
        String currentPage = req.getParameter("currentPage");
        String rows = req.getParameter("rows");
        //默认第1页，5行
        if (currentPage == null || "".equals(currentPage)) {
            currentPage = "1";
        }
        if (rows == null || "".equals(rows)) {
            rows = "5";
        }
        Map<String, String[]> condition = req.getParameterMap();
        PageBean<User_inf> pb = userService.findUserByPage(currentPage, rows, condition);
        req.setAttribute("users", pb);
        req.setAttribute("condition", condition);
        req.getRequestDispatcher("/user/toList").forward(req, resp);

    }

    /**
     * 删除选中
     *
     * @author Lenovo
     * @date 2021/10/8 10:02
     */
    public void delSelected(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String[] ids = req.getParameterValues("id");
        userService.delSelect(ids);
        resp.sendRedirect(req.getContextPath() + "/user/findUserByPage");
    }

    /**
     * 查询单个（用于编辑）
     *
     * @author Lenovo
     * @date 2021/10/8 10:02
     */
    public void findUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取参数
        String id = req.getParameter("id");
        //调用service方法
        User_inf user = userService.findUserById(id);
        //存入request
        req.setAttribute("user", user);
        System.out.println(user);
        //转发到useredit.jsp
        req.getRequestDispatcher("/user/toEdit").forward(req, resp);
    }

    /**
     * 更新
     *
     * @author Lenovo
     * @date 2021/10/8 10:02
     */
    public void updateUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //编码
        req.setCharacterEncoding("utf-8");
        //获取map
        Map<String, String[]> map = req.getParameterMap();
        User_inf user = new User_inf();
        try {
            //封装
            BeanUtils.populate(user, map);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
//        调用service方法
        userService.updateUser(user);
        //重定向回去
        resp.sendRedirect(req.getContextPath() + "/user/findUserByPage");

    }

    /**
     * 添加
     *
     * @author Lenovo
     * @date 2021/10/8 10:03
     */
    public void addUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置编码
        req.setCharacterEncoding("utf-8");
        //获得参数
        Map<String, String[]> map = req.getParameterMap();
        //封装对象
        User_inf user = new User_inf();
        try {
            BeanUtils.populate(user, map);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        //调用service保存
        userService.addUser(user);
        //跳转到findUserByPage
        resp.sendRedirect(req.getContextPath() + "/user/findUserByPage");
    }
}
